package com.rc.common.config;

import com.rc.common.util.RabbitMqHelper;
import com.rc.common.util.RedisHelper;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.MediaType;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.web.client.RestTemplate;

import java.util.List;

/**
 * 工具类配置
 * 配置各种工具类的Bean
 */
@Configuration
public class UtilConfig {

    /**
     * 配置RestTemplate Bean
     * @return 配置好的RestTemplate实例
     */
    @Bean
    public RestTemplate restTemplate() {
        // 配置请求工厂
        SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory();
        // 设置读取超时时间
        factory.setReadTimeout(150000); // 毫秒
        // 设置连接超时时间
        factory.setConnectTimeout(150000); // 毫秒
        // 创建RestTemplate实例
        RestTemplate restTemplate = new RestTemplate(factory);

        // 配置支持的媒体类型
        List<MediaType> mediaTypeList = List.of(MediaType.TEXT_HTML, MediaType.TEXT_PLAIN);

        // 获取消息转换器列表
        List<HttpMessageConverter<?>> messageConverters = restTemplate.getMessageConverters();

        // 配置Jackson转换器以支持文本类型
        for (HttpMessageConverter<?> messageConverter : messageConverters) {
            if (messageConverter instanceof MappingJackson2HttpMessageConverter jacksonConverter){
                jacksonConverter.setSupportedMediaTypes(mediaTypeList);
                break;
            }
        }

        return restTemplate;
    }

    /**
     * 配置RabbitMqHelper Bean
     * @param rabbitTemplate RabbitTemplate实例
     * @return RabbitMqHelper实例
     */
    @Bean
    public RabbitMqHelper rabbitMqHelper(RabbitTemplate rabbitTemplate){
        return new RabbitMqHelper(rabbitTemplate);
    }

    /**
     * 配置RedisHelper Bean
     * @param redisTemplate RedisTemplate实例
     * @return RedisHelper实例
     */
    @Bean
    public RedisHelper redisHelper(RedisTemplate redisTemplate) {
       return new RedisHelper(redisTemplate);
    }
}
